<template>
  <div>
    <div class="container">
      <div class="details-container">
        <div class="placeName">
          <h2>Location: {{ savedPlaceName }}</h2>
          <div>
            <input type="text" v-model="editablePlaceName" placeholder="Edit location name">
            <button @click="savePlaceName" class="btn">Save</button>
            <button @click="resetPlaceName" class="btn">Reset</button>
          </div>
        </div>
        <label for="date" class="input-time">选择日期:</label>
        <input type="date" id="date" v-model="selectedDate" />
        <button @click="saveDateTime" class="btn">保存日期</button>
        <button @click="resetDateTime" class="btn">重置</button>
        <div class="saved-time-box">
          <p>保存的日期: {{ savedDateTime }}</p>
        </div>
      </div>
      <div class="description-editor">
        <h2 class="title"><span class="title-text">文字描述框</span></h2>
        <div class="fixed-description">
          <p>{{ descriptionContent }}</p>
        </div>
        <div class="text-description first-description">
          <textarea v-model="descriptionContent" placeholder="修改你的描述..." class="description-input"></textarea>
          <button class="green-button" @click="saveDescription">保存</button>
        </div>

        <div class = "button-container">
        <div class="text-description.btn">
          <button class="green-button generate-button" @click="showAutoGenerateModal = true">输入关键词,让AI帮你生成描述</button>

        <div v-if="showAutoGenerateModal" class="key-modal">
          <div class="key-modal-content">
            <span class="key-close-button" @click="showAutoGenerateModal = false">&times;</span>
            <h2>AI 自动生成描述</h2>
            <input v-model="keywords" placeholder="输入关键词" />
            <button @click="generateDescription">生成描述</button>
            <p v-if="keydescription">{{ keydescription }}</p>
            <button v-if="keydescription" @click="copyDescription(keydescription)">复制描述</button>
          </div>

        </div>

        </div>
        <!-- Description Editor Component -->
        <div class="text-description.btn">
          <button class="green-button generate-button" @click="showImproveModal=true">润色你的描述</button>

          <div v-if="showImproveModal" class="improve-modal">
          <div class="improve-modal-content">
            <span class="improve-close-button" @click="showImproveModal = false">&times;</span>
            <h2>AI 润色描述</h2>
            <input v-model="initialdes" placeholder="输入初始描述" />
            <button @click="improveDescription">润色描述</button>
            <p v-if="impdescription">{{ impdescription }}</p>
            <button v-if="impdescription" @click="copyDescription(impdescription)">复制描述</button>
          </div>
        </div>

        </div>
        </div>

        <div class = "button-container">
        <div class="text-description.btn">
          <button class="green-button generate-button" @click="showMoodModal = true">AI根据描述生成心情标签</button>
          <div v-if="showMoodModal" class="mood-modal">
          <div class="mood-modal-content">
            <span class="mood-close-button" @click="showMoodModal = false">&times;</span>
            <h2>AI 生成心情标签</h2>
            <textarea v-model="mooddescription" placeholder="请输入描述"></textarea>
            <button @click="generateMood">生成心情标签</button>
            <p v-if="genemood">{{ genemood }}</p>
          </div>
        </div>
        </div>
        
        <div class="text-description.btn">
          <button class="green-button generate-button" @click="generatePhotoModal= true">AI根据文字描述生成图片</button>
          <div v-if="generatePhotoModal" class="genePhoto-modal">
          <div class="genePhoto-modal-content">
            <span class="genePhoto-close-button" @click="generatePhotoModal = false">&times;</span>
            <h2>AI 生成图片</h2>
            <textarea v-model="genePhotodescription" placeholder="请输入描述"></textarea>
            <button @click="generatePhoto">生成图片</button>
            <div v-if="genePhoto">
              <img :src="genePhoto" class="generated-image">
              <p>这是为描述"{{ this.genePhotodescription}}"生成的图片</p>
              <button @click="copyPhotoUrl">复制图片 URL</button>
            </div>
          </div>
        </div>
        </div>

        </div>
      </div>
      
      <div class="mood-add-tags">
        <div class="s-container">
          <div class="moods">情绪标签</div>
        </div>
        <div class="tag-form">
          <input type="text" v-model="newTag.tagName" placeholder="输入标签名称" @keyup.enter="addNewTag" class="tag-input" />
          <select v-model="newTag.moodName" class="tag-select">
            <option value="">选择表情</option>
            <option value="😄">😄</option>
            <option value="😢">😢</option>
            <option value="😡">😡</option>
            <option value="😪">😪</option>
            <option value="🥱">🥱</option>
          </select>
          <button @click="addNewTag" class="tag-button">新建</button>
        </div>
        <div class="tag-list">
        <div v-for="(tag, index) in tags" :key="index" @click="showEditForm(index)">
          <!-- 显示未编辑状态的标签 -->
          <span v-if="editingIndex !== index && tag">
            {{ tag.tagName }}|{{ getMoodIcon(tag.moodName) }}
          </span>
          <!-- 编辑状态的输入框，确保 editingtag 存在且不是 null -->
          <input v-else-if="editingIndex === index && editingtag" type="text" class="edit-input" v-model="safeTagName" @blur="saveEditedTag(index)" />
          <!-- 删除按钮 -->
          <button @click.stop="deleteTag(index)" class="tag-delete-button"></button>
        </div>
    </div>

      </div>

      <button class="btn" @click="openImageModal()">查看关联图片</button>
      <button class="btn" @click="returnyourlocation()">返回地点界面</button>
    </div>

    <!-- Image Modal -->
    <div v-if="showImageModal" class="modal">
      <div class="modal-content">
        <span class="close" @click="closeImageModal">&times;</span>
        <h2>关联图片</h2>
        <div class="image-gallery">
          <div v-for="image in images" :key="image.imageId" class="image-item">
            <img :src="image.imageUrl" alt="Image description">
            <button @click="deleteImage(image.imageId)" class="btn btn-delete">删除</button>
            <button @click="convertImage(image.imageUrl)" class="btn btn-convert">转换成唯美梦幻风格</button>
          </div>
        </div>
        <div>  
          <input type="text" v-model="imageUrl" placeholder="请输入图片 URL" />
          <button @click="addImageUrl" :disabled="!imageUrl" class="btn">增加图片</button>  
        </div>
        <div v-if="convertedImageUrl" class="converted-image">
          <img :src="convertedImageUrl" alt="Converted Image">
          <p>转换后的图片</p>
        </div>
      </div>
    </div>

  </div>
</template>


<script>
import { mapGetters, mapActions } from 'vuex';
import axios from 'axios'; 

export default {
  name: 'LocationInfo',
  props: ['placeId'],
  data() {
    return {
      isLoading: true,
      placeNameInput: '',
      dateInput: '',
      editablePlaceName: '',
      savedPlaceName:'',
      selectedDate: '',
      savedDateTime: '',
      newDescription: '',
      description: [],
      tags: [],
      newTag: { tagName: '', moodName: '' },
      editingIndex: -1,
      editingtag: '',
      editingDescriptionIndex: -1,
      editingDescription: '',
      descriptionContent: '',
      showImageModal: false,
      convertedImageUrl:'',
      images: [], 
      imageUrl: '', 
      emoticons: {
      '😄': '开心',
      '😢': '伤心',
      '😡': '愤怒',
      '😪': '沮丧',
      '🥱': '疲倦',
    },
    showAutoGenerateModal: false,
    keywords: '',
    keydescription : '',
    showImproveModal:false,
    initialdes:'',
    impdescription:'',
    showMoodModal:false,
    mooddescription:'',
    genemood:'',
    generatePhotoModal:'',
    genePhotodescription:'',
    genePhoto:'',
    };
  },
  created() {
    this.loadData();
    this.fetchTags();
  },
  computed: {
    ...mapGetters(['getPlaceById']),
    currentPlace() {
      return this.getPlaceById(this.placeId) || {};
    },
    safeTagName() {
    return this.editingtag ? this.editingtag.tagName : '';
  }
  },
  methods: {
    getMoodIcon(moodName) {
    switch (moodName) {
      case '开心':
        return '😀';
      case '伤心':
        return '😢';
      case '愤怒':
        return '😡';
      case '沮丧':
        return '😪';
      case '疲倦':
        return '🥱';
      default:
        return moodName;
    }
  },
  loadData() {
  console.log('Fetching data for placeId:', this.placeId);  // 调试输出
  return new Promise((resolve, reject) => {
    const token = localStorage.getItem('userToken');
    axios.get(`/api/places/find`, {
      headers: {
        'Authorization': token
      },
      params: { placeId: this.placeId }
    })
    .then(response => {
      console.log('Data loaded:', response.data.data);  // 调试输出
      const place = response.data.data;
      this.savedPlaceName = place.placeName;
      this.selectedDate = place.visitTime;
      this.savedDateTime = place.visitTime;
      this.descriptionContent = place.description;
      resolve();
    })
    .catch(error => {
      console.error('Error loading data:', error);
      reject(error);
    });
  });
},...mapActions(['updatePlaceName', 'updatePlace']),
    saveCurrentPlace(state, { placeName, visitTime, description}) {
      state.currentPlace = { placeName, visitTime, description };
    },
    restoreCurrentPlace(state) {
      return state.currentPlace;
    },
    fetchInitialData() {
      const place = this.getPlaceById(this.placeId);
      if (place) {
        this.editablePlaceName = place.placeName;
        this.selectedDate = place.visitTime;
        this.savedDateTime = place.visitTime;
        this.descriptionContent = place.description; // 直接赋值
      }
    },
    updatePlaceInfo() {
      const updatedPlace = {
        placeId: this.placeId,
        placeName: this.editablePlaceName,
        visitTime: this.savedDateTime,
        description: this.descriptionContent,// 直接传递字符串
        tags:this.tags,
    };
      const token = localStorage.getItem('userToken'); // 从缓存中获取token
      axios.put('/api/places/update', updatedPlace, {
        headers: {
          'Authorization': token
        }
      })
      .then(response => {
        // 更新成功后的处理
        this.updatePlaceInVuex(response.data.data);
        // this.fetchUpdatedData()
        this.loadData()
      })
      .catch(error => {
        console.error('Error updating place info:', error);
        // 错误处理
      });
    },
    saveDescription() {
      this.updatePlaceInfo();
    },
    addNewDescription() {
      if (this.newDescription.trim() !== '') {
        this.description.push(this.newDescription);
        this.updatePlaceInfo(); // 更新后端和Vuex中的数据
        this.newDescription = ''; // 清空输入框
      }
    },
    editDescription(index) {
      this.editingDescriptionIndex = index;
      this.editingDescription = this.description[index];
    },
    saveEditedDescription(index) {
      if (this.editingDescription.trim() !== '') {
        this.$set(this.description, index, this.editingDescription);
        this.updatePlaceInfo(); // 更新后端和Vuex中的数据
        this.editingDescriptionIndex = -1; // 退出编辑模式
        this.editingDescription = '';
      }
    },
    updatePlaceInVuex(updatedPlace) {
      this.$store.dispatch('updatePlace', updatedPlace);
    },
      // 更新地点信息后调用此方法重新从Vuex拉取最新数据
  fetchUpdatedData() {
    const updatedPlace = this.getPlaceById(this.placeId);
    if (updatedPlace) {
      this.editablePlaceName = updatedPlace.placeName;
      this.selectedDate = updatedPlace.visitTime;
      this.descriptionContent = updatedPlace.description;
    }
  },
    savePlaceName() {
      this.updatePlaceInfo();
    },
    resetPlaceName() {
      this.editablePlaceName = this.currentPlace.placeName;
    },
    saveDateTime() {
      if (!this.selectedDate) {
        alert('请选择一个日期');
        return;
      }
      this.savedDateTime = this.selectedDate;
      this.updatePlaceInfo();
    },
    resetDateTime() {
      this.selectedDate = this.currentPlace.visitTime;
      this.savedDateTime = this.currentPlace.visitTime;
    },
fetchTags() {
  console.log(`Fetching tags for placeId: ${this.placeId}`);
  axios.get(`/api/moods/getplacemood`, {
    params: {
      placeId: this.placeId 
    }
  })
  .then(response => {
    this.tags = response.data.data;
    console.log('Tags fetched successfully:', this.tags);
  }).catch(error => {
    console.error('获取标签数据时发生错误:', error);
    alert('加载标签数据失败，请稍后再试');
  });
},
addNewTag() {
  if (!this.newTag.tagName || !this.newTag.moodName) return;
  this.newTag.moodName = this.emoticons[this.newTag.moodName];//很重要
  const moodData = {
    tagName: this.newTag.tagName,
    moodName: this.newTag.moodName,
    placeId: this.placeId,
  };
  axios.post('/api/moods/add', moodData)
  .then(response => {
    this.tags.push(response.data.data);
    this.fetchTags();
    this.resetForm();
    console.log(this.tags); // 查看当前标签列表状态
  })
  .catch(error => {
    console.error('Error adding new mood:', error);
  });
},
deleteTag(index) {
  const tag = this.tags[index];
  axios.delete(`/api/moods/delete`, {
    params: { moodId: tag.moodId }
  })
  .then(() => {
    this.tags.splice(index, 1);
  })
  .catch(error => {
    console.error('Error deleting mood:', error);
  });
},
saveEditedTag(index) {
  const tag = this.tags[index];
  axios.put(`/api/moods/${tag.moodId}`, { name: tag.tagName, moodName: tag.moodName })
    .then(response => {
      this.tags[index] = response.data.data;
      this.resetForm();
    })
    .catch(error => {
      console.error('Error updating mood:', error);
    });
},
showEditForm(index) {
  this.editingIndex = index;
  this.editingtag = { ...this.tags[index] };
},
resetForm() {
  this.newTag = { name: '', moodName: '' };
  this.editingIndex = -1;
  this.editingtag = '';
},
closeImageModal() {  
  this.showImageModal = false;  
  this.selectedFile = null; // 清空选择的文件  
},  
openImageModal() {
  this.fetchImages();
  this.showImageModal = true;
},
fetchImages() {
  axios.get(`/api/images/byPlaceId`, {
    params: {
      placeId: this.placeId 
    }
  })
  .then(response => {
    this.images = response.data.data;//这里真的很容易错
  })
  .catch(error => {
    console.error('Error fetching images:', error);
});
},

addImageUrl() {
    const imageData = {
      placeId: this.placeId,
      imageUrl: this.imageUrl
    };
    axios.post('/api/images/add', imageData, {
     params:{placeId:this.placeId}
    })
    .then(response => {
      console.log('Image URL added successfully:', response);
      alert('图片 URL 添加成功!');
      this.fetchImages(); // 重新获取图片列表，更新界面
      this.imageUrl = ''; // 清空输入框
    })
    .catch(error => {
      console.error('Error adding image URL:', error);
      alert('添加图片 URL 失败，请检查网络或联系管理员！');
    });
  },
deleteImage(imageId) {
  const token = localStorage.getItem('userToken');
  axios.delete('/api/images/delete', {
    headers: {
      'Authorization': token
    },
    params: {
      imageId: imageId
    }
  })
  .then(() => {
    // 从 this.images 数组中删除已删除的图片
    this.images = this.images.filter(image => image.imageId !== imageId);
  })
  .catch(error => {
    console.error('Error deleting image:', error);
  });
},
convertImage() {
  return new Promise(resolve => {
    setTimeout(() => {
      this.convertedImageUrl = 'https://ai-painting-image.vivo.com.cn/ai-painting/763783fb6b8db7a9278b53c6b4c3c291426b0f9e-0.jpg';
      resolve();
    }, 3000);//模拟AI延迟 假数据
  });
},

returnyourlocation(){
  this.$router.push('/location');  
},

generateDescription() {
  return new Promise(resolve => {
    setTimeout(() => {
      // 这里可以调用 AI 模型生成描述
      this.keydescription = `这是为关键词"${this.keywords}"生成的描述`;
      this.keywords = '';
      //刷新输入的关键词
      resolve();
    }, 3000);
  });//假数据
},

copyDescription(description) {
      navigator.clipboard.writeText(description);
      alert('描述已复制到剪贴板');
},

improveDescription(){
  this.impdescription = `这是为初始描述"${this.initialdes}"润色的描述`;
  this.initialdes = '';
  //刷新输入的初始值
},

generateMood()
{
  this.genemood = `这是为描述"${this.mooddescription}"生成的心情标签`;
},

generatePhoto()
{
  return new Promise(resolve => {
    setTimeout(() => {
      this.genePhoto =
  'https://images.unsplash.com/photo-1464925257126-6450e871c667?w=1000&auto=format&fit=crop&q=60&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxzZWFyY2h8Nnx8b2NlYW4lMjB3YXRlcnxlbnwwfHwwfHx8MA%3D%3D';
//示范例子：海洋照片
      resolve();
    },3000) 
})
},

copyPhotoUrl() {
      navigator.clipboard.writeText(this.generatedPhotoUrl);
      alert('图片 URL 已复制到剪贴板');
    },
}}
</script>

<style>
 @import "@/assets/css/LocationInfo.css";
</style>











